package com.atguigu.tingshu.common.minio.service.impl;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.minio.config.MinioProperties;
import com.atguigu.tingshu.common.minio.service.FileUploadService;
import com.atguigu.tingshu.common.util.MD5;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.StatObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @BelongsProject: tingshu-backend
 * @BelongsPackage: com.atguigu.tingshu.album.service.impl
 * @Author: coilk
 * @CreateTime: 2025-03-13  11:25
 * @Description:
 * @Version: 1.0
 */
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {

    //配置类
    @Autowired
    private MinioProperties minioProperties;
    //MinIO客户端
    @Autowired
    private MinioClient minioClient;


    @Override
    public String fileUploadService(MultipartFile file) {
        //存储文件唯一表示
        String objectKey = "";
        //原始名称
        String originalFilename = file.getOriginalFilename();
        try {
            //生成md5文件名
            byte[] bytes = file.getBytes();
            String s = new String(bytes);
            String prefix = MD5.encrypt(s);
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
            objectKey = prefix + suffix;

            //检查文件是否已经存在
            StatObjectArgs statObjectArgs = StatObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(objectKey)
                    .build();
            minioClient.statObject(statObjectArgs);

            //文件已经存在 直接返回url
            return minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + objectKey;
        } catch (IOException e) {
            log.error("上传的文件不存在原因：{}", e.getMessage());
            throw new GuiguException(201, "文件不存在");
        } catch (Exception e) {
            //文件不存在,执行上传
            try {
                PutObjectArgs.Builder putObjectArgsBuilder = PutObjectArgs.builder();
                PutObjectArgs putObjectArgs = putObjectArgsBuilder
                        .bucket(minioProperties.getBucketName())
                        .object(objectKey)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .build();
                minioClient.putObject(putObjectArgs);
                log.info("上传文件到minio成功");
                // 5.将图片地址返回
                return minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + objectKey;
            } catch (Exception subE) {
                log.error("上传文件到minio中失败：{}", subE.getMessage());
                throw new GuiguException(201, "上传文件到minio中失败");
            }
        }
    }
}
